﻿using System;
using NHibernate;

namespace Lucid.ESA.ClientDataSystem.Data.Common
{
    /// <summary>
    /// Class for providing NHibernate Transaction objects.
    /// </summary>
    public class TransactionProvider : ITransactionProvider
    {
        private ITransaction _transaction;

        /// <summary>
        /// Begins a Transaction in the current Session.
        /// </summary>
        public void BeginTransaction()
        {
            _transaction = SessionProvider.GetCurrentSession().BeginTransaction();
        }

        /// <summary>
        /// Commits the Transaction in the current Session.
        /// </summary>
        public void CommitTransaction()
        {
            _transaction.Commit();
            _transaction = null;
        }

        /// <summary>
        /// Rolls back the Transaction in the current Session.
        /// </summary>
        public void RollbackTransaction()
        {
            _transaction.Commit();
            _transaction = null;
        }

        /// <summary>
        /// For implementing IDisposable.
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_transaction != null) RollbackTransaction();
            }
        }

        /// <summary>
        /// For implementing IDisposable.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Destructor.
        /// </summary>
        ~TransactionProvider()
        {
            Dispose(false);
        }
    }
}
